const fs = require('fs');
var tools = require('../libs/tools');
var md5 = require('md5');
module.exports = {
    uniq: function () {
        return md5(new Date().getTime() + Math.random());
    },
    p: function (v) {
        console.log(v);
    },
    copy_setting: function (moduleid) {
        let setting_file = tools.appPath + `/setting/${moduleid}.json`;
        if (!fs.existsSync(setting_file)) {
            fs.copyFileSync(tools.appPath + '/setting/0.json', tools.appPath + `/setting/${moduleid}.json`);
        }
    },
    load_setting: function (moduleid) {
        let setting_file = tools.appPath + `/setting/${moduleid}.json`;
        let setting = {};
        if (fs.existsSync(setting_file)) {
            setting = fs.readFileSync(setting_file);
            setting = JSON.parse(setting);
        }
        return setting;
    },
    save_setting: function (moduleid, post) {
        let setting_file = tools.appPath + `/setting/${moduleid}.json`;
        if (Object.keys(post).length > 0) {
            return this.json_save(post, setting_file);
        }
        return false;
    },
    json_save: function (array, file) {
        let data = JSON.stringify(array);
        fs.writeFileSync(file, data);
        return true;
    },
    //https://www.jb51.net/article/107406.htm
    getUrlByParam: function (param) {
        var url = "";
        for (field in param) {
            if (Array.isArray(param[field])) {
                let newFieldName = '';
                if (field.indexOf('[]') > -1) {
                    newFieldName = field;
                } else {
                    newFieldName = `${field}[]`;
                }
                let tmp = [];
                for (let i = 0; i < param[field].length; i++) {
                    tmp.push(`${encodeURIComponent(newFieldName)}=${encodeURIComponent(param[field][i])}`);
                }
                tmp = tmp.join('&');
                url += "&" + tmp;
            } else {
                url += "&" + encodeURIComponent(field) + "=" + encodeURIComponent(param[field]);
            }
        };
        return url == "" ? url : url.substring(1);
    },
    pagination: function (url, param, page, pagesize, total) {
        page = parseInt(page);
        let total_page = Math.ceil(total / pagesize);
        let previous_disabled = "";
        let next_disabled = "";
        if (page <= 1) {
            previous_disabled = "disabled";
        }
        if (page >= total_page) {
            next_disabled = "disabled";
        }
        let previous_page = Math.max(page - 1, 1);
        let next_page = Math.min(page + 1, total);
        let first_page = 1;
        let last_page = total_page;

        let _p1 = param;
        let p1 = this.getUrlByParam(Object.assign(_p1, { page: previous_page }));
        let _p2 = param;
        let p2 = this.getUrlByParam(Object.assign(_p2, { page: next_page }));
        let _p3 = param;
        let p3 = this.getUrlByParam(Object.assign(_p3, { page: first_page }));
        let _p4 = param;
        let p4 = this.getUrlByParam(Object.assign(_p4, { page: last_page }));
        let _p5 = Object.assign({}, param);
        delete _p5.page;
        let p5 = this.getUrlByParam(_p5);

        let url1 = '';
        let url2 = '';
        let url_first = '';
        let url_last = '';
        if (url.indexOf('?') > -1) {
            url1 = url + '&' + p1;
            url2 = url + '&' + p2;
            url_first = url + '&' + p3;
            url_last = url + '&' + p4;
        } else {
            url1 = url + '?' + p1;
            url2 = url + '?' + p2;
            url_first = url + '?' + p3;
            url_last = url + '?' + p4;
        }
        if (previous_disabled == 'disabled') {
            url_first = url1 = 'javascript:void(0);';
        }
        if (next_disabled == 'disabled') {
            url_last = url2 = 'javascript:void(0);';
        }

        let html = `
        <script>
        function EnterPress(e){
            var e = e || window.event; 
            if(e.keyCode == 13){ 
                var page=Math.abs(parseInt(e.target.value));
                if(!page) return;
                if(page>${total_page}) return;
                location.href='${url}${url.indexOf('?') > -1 ? '&' : '?'}${p5}&page='+page;
            }
        }
        </script>
        <div class="paging_simple_numbers" style="width:500px;margin:0 auto;">
        <ul class="pagination">
          <li class="paginate_button page-item ${previous_disabled}">
          <a href="${url_first}" class="page-link">首页</a>
          </li>
          <li class="paginate_button page-item previous ${previous_disabled}">
          <a href="${url1}" class="page-link">上一页</a>
          </li>
          <li class="paginate_button page-item active">
          <a href="javascript:void(0);" class="page-link">${page}/${total_page} [共${total}条]</a>
          </li>
          <li class="paginate_button page-item next ${next_disabled}">
          <a href="${url2}" class="page-link">下一页</a>
          </li>
          <li class="paginate_button page-item ${next_disabled}">
          <a href="${url_last}" class="page-link">尾页</a>
          </li>
          &nbsp;&nbsp;
          <li class="paginate_button page-item">
          <input type="text" placeholder="页码" value="" size="2" style="margin-top:4px;" onkeyup="EnterPress()">
          </li>
        </ul>
      </div>
`;
        return html;
    },
    myswitch: function (kvalue, array) {
        return array.hasOwnProperty(kvalue) ? array[kvalue] : '';
    },
    //https://www.cnblogs.com/cherishnow/p/10524466.html
    dtrim: function (obj) {
        if (Array.isArray(obj)) {
            obj.forEach((v, k) => {
                obj[k] = this.dtrim(obj[k]);
            });
        } else if (Object.prototype.toString.call(obj) === '[object Object]') {
            Object.keys(obj).forEach((k) => {
                obj[k] = this.dtrim(obj[k]);
            });
        } else {
            obj = obj.replace(/(^\s+)|(\s+$)/g, "");
        }
        return obj;
    },
    //现在的时间戳
    ////https://www.cnblogs.com/fozero/p/6959946.html
    time: function () {
        return parseInt(new Date().getTime() / 1000);
    },
    //2019-12-12 23:59:59 转 时间戳
    strtotime: function (str) {
        if (!str) return 0;
		if (String(str).indexOf(':') == -1) str = str + ' 00:00:00';
        return parseInt(new Date(str).getTime() / 1000);
    },
    // 格式化日期，如月、日、时、分、秒保证为2位数
    formatNumber: function (n) {
        n = n.toString()
        return n[1] ? n : '0' + n;
    },
    // 参数number为毫秒时间戳，format为需要转换成的日期格式
    //data(value, 'Y-M-D h:m:s');
    date: function (number = '', format = 'Y-M-D h:m:s') {
        if (!number) {
            number = this.time();
        }
        let time = new Date(number * 1000);
        let newArr = [];
        let formatArr = ['Y', 'M', 'D', 'h', 'm', 's'];
        newArr.push(time.getFullYear());
        newArr.push(this.formatNumber(time.getMonth() + 1));
        newArr.push(this.formatNumber(time.getDate()));

        newArr.push(this.formatNumber(time.getHours()));
        newArr.push(this.formatNumber(time.getMinutes()));
        newArr.push(this.formatNumber(time.getSeconds()));

        for (let i in newArr) {
            format = format.replace(formatArr[i], newArr[i])
        }
        return format;
    },
    array_merge: function (a, b) {
        return a.concat(b);
    },
    object_merge: function (a, b) {
        let o = {};
        return Object.assign(o, a, b);
    },
    //http://www.manongjc.com/article/17174.html
    str_repeat: function (str, num) {
        return num > 1 ? str.repeat(num) : str;
    },
    in_array: function (value, arr) {
        return arr.indexOf(value) > -1;
    },
    in_object: function (key, obj) {
        key += '';
        return typeof (obj[key]) != 'undefined';
    },
    //https://www.jianshu.com/p/cbdd58749489
    empty: function (d) {
        if (d.constructor === Array) {
            return d.length > 0;
        } else {
            return Object.keys(d).length > 0;
        }
    },
    //https://blog.csdn.net/longzhoufeng/article/details/80195638
    trim: function (str, is_global = '') {
        var result;
        result = str.replace(/(^\s+)|(\s+$)/g, "");
        if (is_global.toLowerCase() == "g") {
            result = result.replace(/\s/g, "");
        }
        return result;
    },
    kv_builder: function (arr, id, name) {
        let d = {};
        arr.forEach((v, k) => {
            d[v[id]] = v[name];
        });
        return d;
    },
    ka_builder: function (arr, id) {
        let d = {};
        arr.forEach((v, k) => {
            d[v[id]] = v;
        });
        return d;
    },
    kc_builder: function (arr, col) {
        if (arr.constructor !== Array) return [];
        let d = [];
        arr.forEach((v, k) => {
            d.push(v[col]);
        });
        return d;
    },
    //https://www.npmjs.com/package/node-fetch
    get: function () {

    },
    post: function () {

    },
    //http://es6.ruanyifeng.com/#docs/set-map#Map
    object2Map: function (obj) {
        let m = new Map();
        for (let i in obj) {
            m.set(i, obj[i]);
        }
        return m;
    },
    //https://www.cnblogs.com/FallIntoDarkness/p/9757334.html
    extension: function (filename) {
        let index = filename.lastIndexOf(".");
        if (index == -1) return '';
        let suffix = filename.substr(index + 1).toLowerCase();
        return suffix;
    },
    //生成从minNum到maxNum的随机数
    //https://www.cnblogs.com/wenxuehai/p/10285585.html
    randomNum: function (minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                //或者 Math.floor(Math.random()*( maxNum - minNum + 1 ) + minNum );
                break;
            default:
                return 0;
                break;
        }
    }

};